// packageLive/pages/cutPrice/cutPriceActivity/cutPriceActivity.js
var util = require('../../../../utils/util')   //引入配置公共请求接口
import { spellApi } from '../../../../config/config'
var configUrl = require('../../../../config/config') //引入配置接口文件
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    footprintGuid: '', //足迹全局id
    statusHeight: app.globalData.StatusBar,
    imgUrl: getApp().globalData.imgUrl,
    activityId: '',
    activityData: '',
    pageBgColor: '',
    titleHeight: '',
    /**-合伙人--*/
    isShowPartnerAll: 1,
    showPartnerCodePop: false,
    timer: "",                                                     // 倒计时定时器名称
    authorizationPopup: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.getLogin((re)=>{
      if(!re){
        this.setData({
          authorizationPopup: true
        })
      }
    })
    var that = this
    wx.getSystemInfo({
      success(res) {
        let statusBarHeight = res.statusBarHeight + 65
        let listMargintop = res.statusBarHeight + 65 + 59
        that.setData({
          titleHeight: statusBarHeight + 'px',
          listMargintop: listMargintop + 'px'
        })
      }
    })
    if (!wx.getStorageSync('addrCode').provinceCode) {
      app.getUserLocation() //初始化获取定位地址
    }
    if (!wx.getStorageSync('loginMsg').token) {
      app.initLogin() //初始化登录
    }
    var temporaryAddressData = wx.getStorageSync('temporaryAddressData')
    var parms = {
      areaCode: wx.getStorageSync('addrCode').provinceCode
    }
    if (options.scene || options.hid) {
      console.log('options888888888888888', options)
      var scene = options.hid ? options.hid : decodeURIComponent(options.scene) //参数二维码传递过来的参数
      if (options.scene) {
        app.getShareCode(scene, (res) => {
          that.setData({
            activityId: options.id
          })
          parms.id = options.id
          var stInFun = setInterval(() => {
            if (wx.getStorageSync('getLocation') === 'N') {
              that.setData({
                showSetting: true
              })
            }
            if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
              that.setData({
                showSetting: false
              })
              clearInterval(stInFun)
              if (!wx.getStorageSync('loginMsg').loginState) {
                if (wx.getUserProfile) {
                  app.getUserProfile(function(){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  })
                } else {
                  if(!wx.getStorageSync('loginMsg').bindingPhone){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  }
                }
                // this.setData({
                //   isShowGetUserInfo: true
                // })
              }
              app.bindingPartner(res.userId)
              that.getActivity(res.id)
            }
          }, 500)
        })
      } else if (options.hid) {
        var shareData={userId:options.hid}
        wx.setStorageSync('shearData', shareData)
        that.setData({
          activityId: options.id
        })
        parms.id = options.id
        var stInFun = setInterval(() => {
          if (wx.getStorageSync('getLocation') === 'N') {
            that.setData({
              showSetting: true
            })
          }
          if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
            that.setData({
              showSetting: false
            })
            clearInterval(stInFun)
            if (!wx.getStorageSync('loginMsg').loginState) {
              if (wx.getUserProfile) {
                app.getUserProfile(function(){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                })
              } else {
                if(!wx.getStorageSync('loginMsg').bindingPhone){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                } else {
                  callback(true)  //低版本微信绑过电话视为已登录
                }
              }
            }
            app.bindingPartner(options.hid)
            that.getActivity(options.id)
          }
        }, 500)
      }
    } else {
      that.setData({
        temporaryAddressData: temporaryAddressData,
        activityId: options.id
      })
      that.getActivity(options.id)
    }
  },
  goreBack: function (e) { //返回
    wx.navigateBack({
      delta: 1
    })
  },
  goHome: function (e) { //返回主页
    wx.reLaunch({
      url: '/pages/newIndex/newIndex'
    })
  },
  getScroll(e) { //监听滑动
    var scorll = e.detail.scrollTop
    if (scorll > 50 && scorll < 150) {
      this.setData({
        headerClass: 'headerClass1',
        tableIsHidden: false,
        returnBoxgo: 'returnBoxgo'
      });
    } else if (scorll > 150) {
      this.setData({
        headerClass: 'headerClass2',
        tableIsHidden: false,
        returnBoxgo: 'returnBoxgo',
      });
    } else if (scorll < 50) {
      this.setData({
        headerClass: 'headerClass3',
        tableIsHidden: true,
        returnBoxgo: '',
      });
    }
    if (scorll < 500) {
      this.setData({
        fontText: 1
      });
    } else if (scorll > 500 && scorll < 1100) {
      this.setData({
        fontText: 2
      });
    } else {
      this.setData({
        fontText: 3
      });
    }
  },
// 获取活动内容
getActivity(id) {
  let that = this
  app.reqFun.requestJson('get', spellApi.cutActivity+id, '', (res) => {
    console.log('砍价砍价砍价', res)
    if (res.data.success == 1) {
      let data = res.data.data
      var time = ''
      if (data.status == 'ongoing') {
        time = data.endTime
      }
      if (data.status == 'unStart') {
        time = data.startTime
      }
      that.getReturnTime(time)
      data.ruleText = data.ruleText.replace(/<img/g, "<img style='width:100%;height:auto;'").replace(/http:\/\//g, 'https://')
      that.setData({
        activityData: data,
        pageBgColor: data.pageBgColor
      })
    }
  })
},
goodsInfo(option) {
  // this.getLogin((re)=>{
  //   if(re){
    let skuid = option.currentTarget.dataset.skuid
    wx.navigateTo({
      url: '/packageShop/pages/goodsInfo/goodsInfo?id=' + skuid,
    })
//   }
// })
},
getReturnTime(time) { //处理活动倒计时--time=活动结束时间
  let that = this;
      that.setData({
        timer: setInterval(function(){
           var lefttime = parseInt((new Date(time.replace(/-/g,"/")).getTime() - new Date().getTime()));
           if(lefttime <= 0) {
             that.setData({
              returnTime:{day:"00",hours:"00",minute:"00",second:"00"}
             })
             clearInterval(that.data.timer);
             return;
           }

           var d = parseInt(lefttime /1000 /3600 /24);  //天数
           var h = parseInt(lefttime / 1000 / 3600 % 24); //小时
           var m = parseInt(lefttime / 1000 / 60 % 60);    //分钟
           var s = parseInt(lefttime / 1000  % 60);        //当前的秒

           d < 10 ? d = "0" + d : d;
           h < 10 ? h = "0" + h : h;
           m < 10 ? m = "0" + m : m;
           s < 10 ? s = "0" + s : s;

           that.setData({
            returnTime:{ day: d, hours: h, minute: m, second:s }
           })
        },1000)
      })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      footprintGuid: util.guid()
    })
    setTimeout(()=>{
      this.setData({
        partnerInfo:getApp().globalData.partnerInfo
      })
      },500)
    if (this.data.activityId) {
      //保存访问足迹
      app.saveAccessFootprint(this.data.footprintGuid, 'cutPriceActivity', this.data.activityId)
    } else {
      //拿到资源id再记录足迹
      var footprintWaitResourceIdTimer = setInterval(()=>{
        if(this.data.activityId){
          //保存访问足迹
          app.saveAccessFootprint(this.data.footprintGuid, 'cutPriceActivity', this.data.activityId)
          clearInterval(footprintWaitResourceIdTimer)
        }
      }, 100)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that=this
    var activityId = that.data.activityId //商品id
    var userId = wx.getStorageSync('loginMsg').userId
    var activityName = that.data.activityData.name
    let path = `/packageLive/pages/cutPrice/cutPriceActivity/cutPriceActivity`
    // let query = `?id=` + activityId
    let query = `?id=${activityId}&hid=${wx.getStorageSync('loginMsg').userId}`
    // 保存分享记录
    app.insertShareRecord(path, query, activityId, 'cutPrice', userId)
    return {
      title: activityName,
      path: path + query
    }
  },
    //展开合伙人信息
    showPartnerAll: function () {
      let isShowPartnerAll;
      if (this.data.isShowPartnerAll == 1) {
        isShowPartnerAll = 0;
      } else {
        isShowPartnerAll = 1;
      }
      this.setData({
        isShowPartnerAll: isShowPartnerAll,
      })
    },
    //展示合伙人二维码
    partnerCode: function (e) {
      // this.setData({
      //   showPartnerCodePop: true,
      // })
      let codeImg=e.target.dataset.url
      wx.previewImage({
        urls:[codeImg],
        current: codeImg, // 当前显示图片的http链接
       })
    },
    //关闭合伙人二维码
    closeCodePop: function () {
      this.setData({
        showPartnerCodePop: false,
      })
    },
    //拨打合伙人电话
    partnerPhone: function () {
      let that = this;
      wx.makePhoneCall({
        phoneNumber: that.data.partnerInfo.partnerPhone,
      })
    }
})